package com.yunban.project.template.utils;

import cn.hutool.core.lang.tree.Tree;
import com.alibaba.fastjson2.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author: lijiajun
 * @date: 2025-03-06
 * @version: 1.0
 */
@Slf4j
public class PromptUtils {
    /**
     * 将树状结构转换为目标字符串
     * - level = 1 的节点作为标题
     * - level = 2 和 level = 3 的节点作为内容
     */
    public static String buildPrompt(List<Tree<Long>> trees) {
        // 将 List<Tree<Long>> trees 转为 List<PromptTree> promptTrees  好做提示词拼接
        List<PromptTree> promptTrees = JSON.parseArray(JSON.toJSONString(trees), PromptTree.class);
        log.info("promptTrees:{}", JSON.toJSONString(promptTrees));
        StringBuilder sb = new StringBuilder();
        for (PromptTree tree : promptTrees) {
            // 添加 level = 1 的节点作为标题
            sb.append("\n").append(tree.getPrompt()).append("\n");
            if (tree.getChildren() != null) {
                for (PromptTree child : tree.getChildren()) {
                    // 添加 level = 2 的节点
                    if (child.getLevel() == 2) {
                        sb.append(child.getPrompt());
                        // 如果 level = 2 的节点有子节点（level = 3），则合并为一行
                        if (child.getChildren() != null && !child.getChildren().isEmpty()) {
                            sb.append(child.getChildren().get(0).getPrompt());
                        }
                        sb.append("\n");
                    }
                }
            }
        }
        return sb.toString();
    }

    @Data
    public static class PromptTree {
        private long id;
        private long parentId;
        private int weight;
        private String name;
        private boolean hasDefault;
        private int level;
        private String prompt;
        private List<PromptTree> children;
    }
}
